﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace gt.rediscache.plugins
{
    internal sealed class HttpClientUtility
    {
        private HttpClientUtility() { }
        private static HttpClient client = new HttpClient();

        public static string Post(string url, string jsonData)
        {
            using (HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json"))
            {
                HttpResponseMessage response = client.PostAsync(url, content).Result;
                string result = string.Empty;
                if (response != null && response.IsSuccessStatusCode) result = response.Content.ReadAsStringAsync().Result;
                return result;
            }
        }

        public static async Task<string> PostAsync(string url, string jsonData)
        {
            using (HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json"))
            {
                HttpResponseMessage response = await client.PostAsync(url, content);
                string result = string.Empty;
                if (response != null && response.IsSuccessStatusCode) result = response.Content.ReadAsStringAsync().Result;
                return result;
            }
        }

        public static string Get(string url, Dictionary<string, string> parameters)
        {
            if (parameters != null) url = BuildUrlWithParams(url, parameters);
            HttpResponseMessage response = client.GetAsync(url).Result;
            string result = string.Empty;
            if (response != null && response.IsSuccessStatusCode) result = response.Content.ReadAsStringAsync().Result;

            return result;
        }

        private static void AddHeadToHttpClient(HttpClient client, Dictionary<string, string> heads)
        {
            foreach (var head in heads)
            {
                client.DefaultRequestHeaders.Add(head.Key, head.Value);
            }
        }

        private static string BuildUrlWithParams(string url, Dictionary<string, string> parameters)
        {
            StringBuilder s = new StringBuilder(url);
            if (!url.Contains("?")) s.Append("?");
            else s.Append("&");
            foreach (var param in parameters)
            {
                s.Append(param.Key).Append("=").Append(param.Value);
                s.Append("&");
            }
            s.Remove(s.Length - 1, 1);
            return s.ToString();
        }

    }
}
